package com.ajie.bluetoothcard.ui;



import java.util.ArrayList;

import com.ajie.bluetoothcard.adapter.CardAdapter;
import com.ajie.bluetoothcard.db.DBApi;
import com.ajie.bluetoothcard.domain.Card;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;


/**
 * 回收站
 */
public class MainBackCardActivity extends BaseActivity  {
	private Button del_all_button,del_button,back_box_button;
	private ListView listView;
	private DBApi dbApi;
	private ArrayList<Card> cards = new ArrayList<Card>();
	private CardAdapter cardAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.back_card);
		showTop(R.string.back_card, true);
		dbApi = DBApi.getInstance(this);
		initView();
	}
	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		super.initView();
		del_all_button = (Button) findViewById(R.id.del_all_button);
		del_all_button.setOnClickListener(this);
		del_button = (Button) findViewById(R.id.del_button);
		del_button.setOnClickListener(this);
		back_box_button = (Button) findViewById(R.id.back_box_button);
		back_box_button.setOnClickListener(this);
		listView = (ListView) findViewById(R.id.list);
		cardAdapter = new CardAdapter(this);
		listView.setAdapter(cardAdapter);
		refres();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.del_button:
			startActivityForResult(new Intent(this,DelCardListActivity.class).putExtra("cards",cards).putExtra("isDel", true),20001);
			break;
		case R.id.del_all_button:
			if(cards.size()>0){
				delAllCard();
			}
			break;
		case R.id.back_box_button:
			if(cards.size()>0){
				backToBox();
			}
			break;

		default:
			break;
		}
	}
	private void delAllCard() {
		for (int i = 0; i < cards.size(); i++) {
			dbApi.delCard(cards.get(i).getId());
		}
		refres();
		showToast("删除完成");
	}
	private void backToBox() {
		for (int i = 0; i < cards.size(); i++) {
			Card card = cards.get(i);
			card.setIsDel("0");
			dbApi.updateRecord(card);
		}
		refres();
		showToast("还原结束");
	}
	private void refres() {
		cards = dbApi.getAllCardsByType(DBApi.SEARCHTYPE_ALL,"","","1");
		cardAdapter.setData(cards);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 20001:
			refres();
			break;
		default:
			break;
		}
	}
}
